const {resolve} = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')

// 配置ENV
process.env.NODE_ENV = 'production'


module.exports = {
  entry: "./src/js/index.js",
  output: {
    path: resolve(__dirname, "build"),
    filename: "js/bundle.js"
  },
  module: {
    rules: [
      // 打包样式到独立文件
      {
        test: /\.(le|c)ss$/,
        use: [
          // 'style-loader',
          {
            loader: MiniCssExtractPlugin.loader,  // 提取独立css文件的loader
            options: {
              publicPath: '../', // 这个参数很重要，影响css中url中路径
            }
          },
          'css-loader',
          /*
          css兼容性处理:postcss: 安装postcss-loader,postcss-preset-env
          在package.json中设置browserslist
          "browserslist": {
            "development": [
              "last 5 chrome version",
              "last 5 firefox version",
              "last 5 safari version"
            ],
            "production": [
              ">0.2%",
              "not dead"
            ]
          }
          */
          {
            loader: 'postcss-loader',
            options: {
              ident: 'postcss',
              plugins: () => [
                require('postcss-preset-env')(),  // css兼容
              ]
            }
          },
          'less-loader'
        ],
      },
      // 打包图片
      {
        test: /\.(jpg|jpeg|png|gif)$/,
        loader: 'url-loader',
        options: {
          limit: 8 * 1024,
          outputPath: 'imgs' // 指定输出目录
        }
      },
      {
        test: /\.html$/,
        loader: 'html-loader', // 处理HTML中的img标签图片
      },
      // 打包其他资源
      {
        exclude: /.(html|css|less|jpg|jpeg|png|gif)/,
        loader: 'file-loader',
        options: {
          outputPath: 'media'
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin(
      {
        template: './src/index.html'
      }
    ),
    // 提取独立的css文件 插件:mini-css-extract-plugin
    new MiniCssExtractPlugin({
      filename: 'css/index.css'
    }),
    // 压缩css
    new OptimizeCssAssetsWebpackPlugin()
  ],
  mode: "production",
  devServer: {
    contentBase: resolve(__dirname, 'build'),
    compress: true,
    port: 9002,
    open: true
  }
}